package com.notebook.controller.app;

import com.notebook.dto.Dto;
import com.notebook.entity.pojo.*;
import com.notebook.entity.vo.news.*;
import com.notebook.entity.vo.user.ShowUser;
import com.notebook.service.MessageService.IMessageService;
import com.notebook.service.NewsCommService.NewsCommServiceImpl;
import com.notebook.service.NewsLikeService.NewsLikeServiceImpl;
import com.notebook.service.NewsService.NewsServiceImpl;
import com.notebook.service.UserService.IUserService;
import com.notebook.service.favoriteService.FavoriteServiceImpl;
import com.notebook.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsServiceImpl newsService;
    @Autowired
    private NewsLikeServiceImpl newsLikeService;
    @Autowired
    private FavoriteServiceImpl favoriteService;
    @Autowired
    private NewsCommServiceImpl newsCommService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IMessageService messageService;
    @RequestMapping
    @ResponseBody
    public Dto HomeNewsList() {
        Dto dto = new Dto();

        List<HomePageNewsVO> list = newsService.HomeNewsList();
        dto.setData(list);
        dto.setSuccess(true);
        return dto;
    }

    @RequestMapping(value = "/upload")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("type")String  type,
                                      HttpServletRequest request,
                                      HttpServletResponse response){
        String pathName;
        if(type.equals("news")){
            pathName="/../asset/NewsImage/"+DateUtil.getDateDirName()+"/"+ DateUtil.getDateFileName();
        }else{
            pathName="/../asset/VersionImage/"+DateUtil.getDateDirName()+"/"+ DateUtil.getDateFileName();
        }
        return UpLoadUtil.upLoad(pathName,request,response);
    }


    //按id查询单条
    @RequestMapping(value = "/findById", method = RequestMethod.POST)
    @ResponseBody
    public Dto selectByPrimaryKey(
            @RequestParam("newsId") Integer newsId,
            @RequestParam("deviceId") String deviceId,
            @RequestParam("userId") int userId) {
        Dto dto = new Dto();
        //根据id查询新闻详情
        News news = newsService.selectByPrimaryKey(newsId);
        //查询当前设备有没有赞过这条新闻
        NewsLike newsLike = new NewsLike(newsId, deviceId);
        Integer count = newsLikeService.GetYesNoLike(newsLike);
        if (count != null) {
            dto.setSuccess(true);
        }
        //判断用户是否登录
        if (userId != 0) {
            //查询当前用户有没有收藏此新闻
            Favorite favorite = new Favorite(userId, newsId);
            Integer favoId = favoriteService.getYesNoFavo(favorite);
            if (favoId != null) {
                dto.setMessage("1");
            }
        }
        //增加新闻阅读数
        boolean addYesNo = newsService.addNewsClickNum(newsId);

        //获取新闻阅读数
        Integer ClickNumber = newsService.getNewsClickNum(newsId);
        //设置阅读数
        news.setClickNumber(ClickNumber);

        //获取当前新闻点赞数
        Integer NewsNum = newsLikeService.GetNewsLike(newsId);
        //设置点赞数量
        news.setNewsLikeNum(NewsNum);
        //获取当前新闻的全部评论
        List<NewsComm> newsComms = newsCommService.findByNewsId(newsId);
        for (NewsComm item : newsComms) {
            //获取该评论的用户信息
            NewsCommUserVO userVO = newsCommService.getNewsCommUser(item.getCommUserId());
            item.setNewsCommUserVO(userVO);
        }
        Map<String, Object> map = new HashMap<String, Object>(0);
        map.put("newsComm", newsComms);
        news.setMap(map);
        //返回转发数
        news.setNewsIntrNum(0);
        //返回用户显示信息
        ShowUser showUser = userService.getUserInfo(news.getNewsUserId());
        news.setShowUser(showUser);
        //把新闻详情带过去
        dto.setData(news);

        return dto;
    }




    @RequestMapping(value = "/getNews", method = RequestMethod.POST)
    @ResponseBody
    public Dto getNews(String type, int num) {
        Dto dto = new Dto();
        List<GetNewsVO> getNewsVOS = newsService.getNews(type, num);
        if (getNewsVOS.size() != 0) {
            dto.setSuccess(true);
            dto.setData(getNewsVOS);
        }
        return dto;
    }









    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Dto userNewsDelete(@PathVariable("id") Integer id) {
        boolean yesno = newsService.deleteByPrimaryKey(id);
        Dto<News> dto = new Dto<News>();
        if (yesno) {
            dto.setSuccess(true);
        }
        return dto;
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Dto updateByPrimaryKey(NewsVo newsVo) {
        Dto dto = new Dto();
        newsVo.setCreateTime(DateUtil.DateToLong());
        newsVo.setNewsContent(newsVo.getNewsContent().replaceAll("닭", "&").replaceAll("풀","%"));
        int count = newsService.updateByPrimaryKey(newsVo);
        if (count > 0) {
            dto.setSuccess(true);
        }
        return dto;
    }




    @RequestMapping(value = "/findByType", method = RequestMethod.POST)
    @ResponseBody
    public Dto FindByNewsType(@RequestParam("newsType") String newsType, @RequestParam("num") Integer num) {
        Dto dto = new Dto();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type", newsType);
        map.put("num", (num - 1) * 5);
        List<NewsByTypeVO> list = newsService.FindByNewsType(map);
        for (NewsByTypeVO item : list) {
            Integer likeNum = newsLikeService.GetNewsLike(item.getNewsId());
            item.setNewsLikeNum(likeNum);
            Integer CommNum = newsCommService.selectCommCount(item.getNewsId());
            item.setNewsRankNum(CommNum);
        }
        dto.setData(list);
        return dto;
    }

    @RequestMapping(value = "/Carousel", method = RequestMethod.POST)
    @ResponseBody
    public Dto Carousel() {
        Dto dto = new Dto();
        List<CarouselNewsVo> list = newsService.carouselList();
        dto.setData(list);
        return dto;
    }

    @RequestMapping(value = "/newsUpload")
    @ResponseBody
    public Map<String,Object> newsUpLoad(
            @RequestParam("phone") String phone,
            HttpServletRequest request,
            HttpServletResponse response){
        String path = "/../asset/NewsUserImage/"+phone+"/"+DateUtil.getDateDirName()+"/";
        Map<String,Object> map = UpLoadUtil.NewsUpLoad(path,request,response);
        String url = map.get("url").toString().substring(4);
        String url1 = "http://140.143.57.236/"+url;
        map.put("url",url1);
        return map;
    }

    @RequestMapping(value = "/addUserNews",method = RequestMethod.POST)
    @ResponseBody
    public Dto AddUserNews(UserNews userNews){
        userNews.setCreateTime(DateUtil.DateToLong());
        Dto dto = new Dto();
        userNews.setNewsContent(userNews.getNewsContent().replaceAll("닭", "&").replaceAll("풀","%"));
        Integer count = newsService.AddUserNews(userNews);
        String path = "/usr/tomcat/webapps/notebook///../asset/LuceneData";
        if(FileUtil.deleteDirectory(path)){
            List<LuceneNewsVo> list = newsService.LuceneNewsList();
            LuceneUtil.IndexWrite(path,list);

        }
        if(count!=null) {
           dto.setSuccess(true);
        }
        return dto;
    }

    @RequestMapping(value = "/getUserNews",method = RequestMethod.POST)
    @ResponseBody
    public Dto GetUserNews(@RequestParam("userId") Integer userId){
        Dto dto = new Dto();
        List<UserNews> list  = newsService.getUserNews(userId);
        if(list.size()==0) {
            dto.setData(-1);
        }else{
            dto.setData(list);
        }
        return dto;
    }

    @RequestMapping(value = "/byId")
    public String FindByNewsId(Integer id,Model model){
        News news = newsService.selectByPrimaryKey(id);
        model.addAttribute("newsInfo",news);
        return "news/shenhe_news";
    }

    @RequestMapping(value = "/selectId",method = RequestMethod.POST)
    @ResponseBody
    public Dto NewsById(Integer newsId){
        News news = newsService.selectByPrimaryKey(newsId);
        Dto dto = new Dto();
        dto.setData(news);
        return dto;
    }

    @RequestMapping(value = "/todayranrankings",method = RequestMethod.POST)
    @ResponseBody
    public Dto getTodayNewsUserInfo(){
        Dto dto = new Dto();
        List<ShowUser> list = newsService.getTodayNewsUserInfo();
        dto.setData(list);
        return dto;
    }
    @RequestMapping(value = "/quarterranrankings",method = RequestMethod.POST)
    @ResponseBody
    public Dto getQuarteNewsUserInfo(){
        Dto dto = new Dto();
        List<ShowUser> list = newsService.getQuarterNewsUserInfo();
        dto.setData(list);
        return dto;
    }
    @RequestMapping(value = "/weekranrankings",method = RequestMethod.POST)
    @ResponseBody
    public Dto getWeekNewsUserInfo(){
        Dto dto = new Dto();
        List<ShowUser> list = newsService.getWeekNewsUserInfo();
        dto.setData(list);
        return dto;
    }
    @RequestMapping(value = "/yearranrankings",method = RequestMethod.POST)
    @ResponseBody
    public Dto getYearNewsUserInfo(){
        Dto dto = new Dto();
        List<ShowUser> list = newsService.getYearNewsUserInfo();
        dto.setData(list);
        return dto;
    }
    @RequestMapping(value = "/monthranrankings",method = RequestMethod.POST)
    @ResponseBody
    public Dto getMonthNewsUserInfo(){
        Dto dto = new Dto();
        List<ShowUser> list = newsService.getMonthNewsUserInfo();
        dto.setData(list);
        return dto;
    }
    @RequestMapping(value = "/getlastnewsinfo",method = RequestMethod.POST)
    @ResponseBody
    public Dto getLastNewsInfo(){
        Dto dto = new Dto();
        List<CarouselNewsVo> list = newsService.getLastNewsInfo();
        dto.setData(list);
        return dto;
    }

}
